package com.bw.unit6

import android.content.Intent
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.unit3.base.BaseActivity
import com.bw.unit3.http.HttpUtil
import com.bw.unit6.bean.UserInfoBean
import com.bw.unit6.databinding.ActivityLoginBinding
import com.bw.unit6.db.DbUtil
import com.bw.unit6.viewmodel.LoginViewModel

@Route(path = "/login/123")
class LoginActivity : BaseActivity<LoginViewModel, ActivityLoginBinding>(R.layout.activity_login) {
    var userBean: UserInfoBean? = null
//    @Autowired
//    lateinit var userName:String
    override fun initData() {
        viewModel.livedataLogin.observe(this) {
            ToastUtils.showShort(it.message)
            if (it.code == 200) {
                SPUtils.getInstance().put("token", it.data.token)
                //给 余额字段赋值
                it.data.money = 1000000f
                //登录成功，保存信息 到本地数据库
                DbUtil.dataBase.getUserInfoDao().insert(it.data)
                startActivity(Intent(this@LoginActivity, GoodsActivity::class.java))
                finish()
            }
        }
    }

    override fun initView() {

//        ARouter.getInstance().inject(this)
//
//        ToastUtils.showShort(userName)

        dataBinding.btn.setOnClickListener {
            if (!HttpUtil.isNet(this@LoginActivity)) {
                ToastUtils.showShort("请开启网络")
                return@setOnClickListener
            }

            val name = dataBinding.etName.text.toString()
            val pass = dataBinding.etPass.text.toString()
            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
                ToastUtils.showShort("用户名或密码不能为空")
                return@setOnClickListener
            }

            val map = HashMap<String, String>()
            map["username"] = name
            map["password"] = pass

            viewModel.login(map)
        }

        userBean = DbUtil.dataBase.getUserInfoDao().getUserInfo()

        //从数据表获取 用
        dataBinding.etName.setText(userBean?.username)

    }

}